package linkedlist;

/**
 * Created by Tzachi on 08/10/2014.
 */
public class Main {

    public static Node<Integer> removeAllNodesWithDataK(Node<Integer> head, int k) {
        if (head == null) return null;

        // make sure head not need to be removed !!
        Node<Integer> returnNode = new Node<>(k * -1);
        returnNode.setNext(head);

	/* head is ok
        1. get value of next node
		2. if need to remove, connect current node to next.getNext()
		3. check again 1, if ok, current = current.next
	*/
        Node<Integer> currentNode = returnNode;
        Node<Integer> nextNode = returnNode.getNext();
        while (nextNode != null) {
            if (nextNode.getData() == k) {
                currentNode.setNext(nextNode.getNext());
            } else {
                currentNode = currentNode.getNext();
            }
            nextNode = nextNode.getNext();
        }
        return returnNode.getNext();
    }


    public static void main(String[] args) {
        /*
        Node head = new Node(0);
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);

        head.setNext(node1);
        node1.setNext(node2);
        node2.setNext(node3);

        System.out.println(nthToLastIterative(head, 3));
        Node nth = new Node(-1);
        nthToLastRecursion(head, nth, 3);
        System.out.println(nth);
        */

        Node head = new Node(4);
        head.chainNext(new Node(8)).chainNext(new Node(8)).chainNext(new Node(12));
        head = removeAllNodesWithDataK(head, 8);
        head.printChain();
    }
}
